package com.yuantu.judiciary.controller;

import com.yuantu.judiciary.model.dto.AccountInfoDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.ObjectUtils;

/**
 * 控制器基础类
 *
 * @author syw
 * @since 2023-08-08
 **/
@Slf4j
public class BaseController {

    /**
     * 获取当前登录账号信息
     */
    public AccountInfoDTO getLoginAccount() {
        AccountInfoDTO authAccount;
        if (ObjectUtils.isEmpty(SecurityContextHolder.getContext())
                || ObjectUtils.isEmpty(SecurityContextHolder.getContext().getAuthentication())
                || ObjectUtils.isEmpty(SecurityContextHolder.getContext().getAuthentication().getPrincipal())
        ) {
            log.error("获取当前登录账号对象失败");
            authAccount = new AccountInfoDTO();
            authAccount.setAccountId(-1L);
            authAccount.setUsername("abnormal_user");
            return authAccount;
        } else {
            Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            log.info("获取当前登录账号对象: {}", principal);
            return (AccountInfoDTO) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        }
    }

}
